/**
 * Class MandatesPage.
 * 
 * @author Maxime Ollagnier
 */
MandatesPage.inherits(Module);
function MandatesPage() {
	
	var that = this;
	
	this.inputCustomProperties = new Array();
	
	/** Inputs modules */
	this.inputDebtor = new InputTextModule({
		'id' : 'inputDebtor',
		'label' : I18n.get('debtor'),
		'placeholder' : I18n.get('debtor.name'),
		'validationPattern' : ValidationPattern.VALID_DEFAULT_SEARCH,
		'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
	});
	this.inputBic = new InputTextModule({
		'id' : 'inputBic',
		'label' : I18n.get('mandate.bic'),
		'placeholder' : I18n.get('mandate.bic'),
		'validationPattern' : ValidationPattern.VALID_DEFAULT_SEARCH,
		'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
	});
	this.inputIban = new InputTextModule({
		'id' : 'inputIban',
		'label' : I18n.get('mandate.iban'),
		'placeholder' : I18n.get('mandate.iban'),
		'validationPattern' : ValidationPattern.VALID_DEFAULT_SEARCH,
		'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
	});
	this.inputICS = new InputTextModule({
		'id' : 'inputICS',
		'label' : I18n.get('mandate.ics'),
		'placeholder' : I18n.get('mandate.ics'),
		'validationPattern' : ValidationPattern.VALID_DEFAULT_SEARCH,
		'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
	});
	this.inputRum = new InputTextModule({
		'id' : 'inputRum',
		'label' : I18n.get('mandate.rum'),
		'placeholder' : I18n.get('mandate.rum'),
		'validationPattern' : ValidationPattern.VALID_RUM,
		'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
	});
	this.inputStatus = new InputSelectModule({
		'id' : 'inputStatus',
		'label' : I18n.get('status'),
		'options' : EnumManager.MandateStatus,
		'onChange' : function(){
			that.changeNotificationStatus();
		}
	});
	this.inputReferrer = new InputReferrerModule({
		'id' : 'inputReferrer',
		'label' : I18n.get('entity'),
		'value' : UserManager.user.referrer,
		'rootReferrer' : UserManager.user.referrer,
		'mandatory' : true,
		'onSelect' : function(referrer) {
			that.setReferrer(referrer);
			that.buildJQ();
		}
	});
    this.inputMandateFlow = new InputSelectModule({
        'id' : 'inputMandateFlow',
        'label' : I18n.get('flow'),
        'defaultValue' : '',
        'onChange' : function(){
            that.changeNotificationStatus();
        }
    });
    this.inputContext = new InputSelectModule({
        'id' : 'inputContext',
        'label' : I18n.get('context'),
        'defaultValue' : '',
        'getText' : function(value, object) {
            if (Util.checkObject(object)) {
                return object.name + ' (' + UserManager.getReferrer(object.creditorId).name + ')';
            }
            return object;
        }
    });
	this.inputMandateOther = new InputSelectModule({
		'id' : 'inputMandateOther',
		'label' : I18n.get('other'),
		'defaultValue' : '',
		'options' : EnumManager.TriggerItemStatus
	});
	
	/** Result table module */
	this.mandateTable = new TableModule();
	this.mandateTable.columnList.push(new Column('debtor', I18n.get('debtor'), '17%', true));
	this.mandateTable.columnList.push(new Column('rum', I18n.get('mandate.rum'), '35%', true));
	this.mandateTable.columnList.push(new Column('creditor', I18n.get('creditor'), '17%', true));
	this.mandateTable.columnList.push(new Column('mandateFlowName', I18n.get('flow'), '16%', true));
	var statusCol = new Column('status', I18n.get('status'), '15%', true, true);
	this.mandateTable.columnList.push(statusCol);
	statusCol.getText = function(mandate) {
		return $('<span class="MandateStatus_' + mandate.status + '">' + I18n.get('MandateStatus.' + mandate.status) + '</span>');
	};
	this.mandateTable.onClickTr = function(jQTr) {
		var mandateId = jQTr.attr('id').split('&');
		var rum = mandateId[0];
		var creditorId = mandateId[1];
		NavigationManager.goTo('MandatePage?mandateRum=' + encodeURIComponent(rum) + '&creditorId=' + creditorId);
	};
	this.mandateTable.pagerShow = true;
	this.mandateTable.pagerMax = 10;
	this.mandateTable.onClickPager = function() {
		that.searchMandates();
	};
}

MandatesPage.neededRoles = ["ROLE_USER", "VIEW_MANDATE"];

MandatesPage.prototype.fillJQ = function(jQ) {
	var that = this;
	
	// Title
	jQ.append($('<h4>' + I18n.get('mandate.search.title') + '</h4>'));

	// Form
	var form = $('<div class="form well row-fluid"></div>');
	jQ.append(form);

	var columnLeft = $('<div class="span6"></div>');
	columnLeft.append(this.inputDebtor.buildJQ());
	columnLeft.append(this.inputBic.buildJQ());
	columnLeft.append(this.inputIban.buildJQ());
	columnLeft.append(this.inputICS.buildJQ());
	var columnRight = $('<div class="span6"></div>');
	columnRight.append(this.inputRum.buildJQ());
	columnRight.append(this.inputStatus.buildJQ());
	columnRight.append(this.inputReferrer.buildJQ());
	columnRight.append(this.inputMandateFlow.buildJQ());
    columnRight.append(this.inputContext.buildJQ());
    if (Object.size(that.inputContext.options) > 0) {
        this.inputContext.show();
    } else {
        this.inputContext.hide();
    }
	columnRight.append(this.inputMandateOther.buildJQ().hide());
	form.append(columnLeft).append(columnRight);
	
	// Custom properties
	if (this.inputCustomProperties.length > 0) {
		
		var customCollapsible = new CollapsibleModule({
			'title' : $('<h5>' + I18n.get('mandate.search.advanced') + '</h5>'),
			'showCollapsibleIcon' : 'prepend',
			'collapsed' : true,
			'effect' : 'none'
		});
		
		var customForm = $('<div class="customForm form cropbottom row-fluid"></div>');
		columnLeft = $('<div class="span6"></div>');
		columnRight = $('<div class="span6"></div>');
		customForm.append(columnLeft).append(columnRight);
		
		customCollapsible.setContent(customForm);
		
		$.each(this.inputCustomProperties, function(index, inputCustomProperty) {
			if (index % 2 == 0) {
				columnLeft.append(inputCustomProperty.buildJQ());
			} else {
				columnRight.append(inputCustomProperty.buildJQ());
			}
		});
		
		form.append(customCollapsible.buildJQ());
		
	}
	
	// Buttons
	var buttonRow = $('<div class="btn-row"></div>');
	form.append(buttonRow);
	
	var buttonSearch = $('<div class="btn search">' + I18n.get('search') + '</div>');
	buttonSearch.click(function() { that.mandateTable.pagerStart = 0; that.searchMandates(); });
	buttonRow.append(buttonSearch);
	
	if (UserManager.hasRoles(['WRITE_MANDATE'])) {
		var buttonNew = $('<div class="btn new">' + I18n.get('mandate.new') + '</div>');
		buttonNew.click(function() { NavigationManager.goTo('MandatePage'); });
		buttonRow.append(buttonNew);
	}
	
	if (UserManager.hasRoles(['UPLOAD_MANDATE'])) {
		var buttonUpload = $('<div class="btn upload">' + I18n.get('mandate.upload.title') + '</div>');
		buttonUpload.click(function() { NavigationManager.goTo('MandateUploadModule'); });
		buttonRow.append(buttonUpload);
	}
	
	// Sets focus on first input field
	this.inputDebtor.getJQ().find('input').focus();
	
	// Result table
	var result = $('<div class="result"></div>');
	result.append($('<br/>'));
	result.append($('<h4>' + I18n.get('mandate.search.list') + '</h4>'));
	jQ.append(result);
	if (this.mandateTable.objectMap.size == 0) {
		result.hide();
	}
	result.append(this.mandateTable.buildJQ());
	
	// Launches the search
	this.searchMandates();
};

/**
 * TODO Comment
 */
MandatesPage.prototype.loadData = function(callback) {
	this.setReferrer(this.inputReferrer.value);
	this.inputReferrer.selectUniqueCreditor();
	Util.getFunction(callback)();
};

/**
 * TODO Comment
 */
MandatesPage.prototype.searchMandates = function() {
	if (!this.validate()) {
		return;
	}
	
	var params = {
		'debtorName' : this.inputDebtor.value,
		'rum' : this.inputRum.value,
		'bic' : this.inputBic.value,
		'iban' : this.inputIban.value,
        'ics' : this.inputICS.value,
		'status' : this.inputStatus.value,
		'notifStatus' : this.inputMandateOther.value,
		'sortBy' : this.mandateTable.sortBy,
		'sortDesc' : this.mandateTable.sortDesc,
		'start' : this.mandateTable.pagerStart,
		'size' : this.mandateTable.pagerMax
	};
	var creditors = this.inputReferrer.getCreditors();
	$.each(creditors, function(index, creditor) {
		params['creditorId' + index] = creditor.id;
	});
	var i = 0;
	$.each(this.inputCustomProperties, function(index, inputCustomProperty) {
		if (Util.checkStringNotEmpty(inputCustomProperty.value)) {
			params['customProperty' + (i++)] = inputCustomProperty.key + '##' + inputCustomProperty.value;
		}
	});
	if (Util.checkString(this.inputMandateFlow.value)) {
		params['mandateFlowId'] = this.inputMandateFlow.value;
	}
    if (Util.checkStringNotEmpty(this.inputContext.value)) {
        params['contextIds'] = '[' + this.inputContext.value + ']';
    } else {
        params['contextIds'] = (function(contexts) {
            var contextIds = '[';
            $.each(contexts, function(id) {
                contextIds += id + ',';
            });
            contextIds = contextIds.length > 1 ? contextIds.substring(0, contextIds.lastIndexOf(',')) : contextIds;
            contextIds += ']';
            return contextIds;
        })(this.inputContext.options);
    }
	
	var that = this;
	AjaxManager.getJSON('getMandates', params, function(result) {
		if (result.success) {
			that.getJQ().find('.result:first').show();
			that.mandateTable.pagerTotal = result.totalCount;
			that.mandateTable.objectMap = new Map();
			for (var i = 0; i < result.mandates.length; i++) {
				that.mandateTable.objectMap.put(result.mandates[i].rum + '&' + result.mandates[i].creditorId, result.mandates[i]);
			}
			that.mandateTable.buildJQ();
		}
	});
};

/**
 * Called when flow selection changed, display or not the notification alarm status of the mandate
 */
MandatesPage.prototype.changeNotificationStatus = function() {
	var that = this;
	if (this.inputStatus.getValue() == '_' || this.inputStatus.getValue() == 'V'){
		var flows = [];
		if (this.inputMandateFlow.getValue() == ''){
			$.each(this.inputMandateFlow.options, function(key, value){
				flows = flows.concat(eval(key));
			});
		} else {
			flows = eval(this.inputMandateFlow.getValue());
		}
		AjaxManager.getJSON('getTriggers', {
			'flows' : JSON.stringify(flows)
		}, function(result) {
			if (result.success) {
				if (Util.checkBoolTrue(result.displayStatus)){
					that.inputMandateOther.show();
				} else {
					that.inputMandateOther.setValue("");
					that.inputMandateOther.buildJQ().hide();
				}
			}
		});
	} else {
		this.inputMandateOther.setValue("");
		this.inputMandateOther.buildJQ().hide();
	}
};

/**
 * Convert an object of mandateFlow (key=id, value=flow) into an object grouping the flow by name.
 * Key are now a list of IDs corresponding to the flow having the same name
 *
 * @param mandateFlow
 * @returns an object containing flowIds of the same name as Key, and flow as value
 */
MandatesPage.groupFlowByName = function(mandateFlow){
	var tmp = {};
	$.each(mandateFlow, function(k, v){
		if (!Util.check(tmp[v.name])){
			tmp[v.name] = [];
		}
		tmp[v.name].push(v);
	});
	var groupedFlows = {};
	$.each(tmp, function(k, v){
		groupedFlows['[' + $.map(v, function(val){ return val.id; }).join(',') + ']'] = k;
	});
	return groupedFlows;
};

/**
 * TODO Comment
 */
MandatesPage.prototype.setReferrer = function(referrer) {

	// Optional data
	this.inputCustomProperties = new Array();
	var that = this;
	$.each(referrer.customProperties, function(i, customProperty) {
		if (customProperty.indexed) {
			var inputCustomProperty = undefined;
			if (customProperty.type == 'CHOICE_LIST') {
				inputCustomProperty = new InputSelectModule({
					'label' : customProperty.name,
					'options' : customProperty.values,
					'defaultValue' : ''
				});
			} else {
				inputCustomProperty = new InputTextModule({
					'label' : customProperty.name,
					'placeholder' : customProperty.name,
					'validationPattern' : ValidationPattern.VALID_DEFAULT,
					'onEnter' : function() { that.mandateTable.pagerStart = 0; that.searchMandates(); }
				});
			}
			inputCustomProperty.key = customProperty.key;
			that.inputCustomProperties.push(inputCustomProperty);
		}
	});
    // Mandate flows
    AjaxManager.getJSON("getAvailableMandateFlowsForUser", {
        'referrerId' : referrer.id
    }, function(result) {
        if (result.success) {
            that.inputMandateFlow.setOptions(MandatesPage.groupFlowByName(result.availableMandateFlowsForUser), true).buildJQ();
            that.inputMandateFlow.onChange();
        }
    });
    // Context
    AjaxManager.getJSON('getAuthorizedContexts', {
        'referrerId' : referrer.id
    }, function(result) {
        if (result.success) {
            that.inputContext.setOptions(result.contexts, true);
            if (Object.size(result.contexts) > 0) {
                that.inputContext.buildJQ().show();
            } else {
                that.inputContext.buildJQ().hide();
            }
        }
    });
};